package com.zcurd.controller;

import java.util.Date;
import java.util.List;

import com.jfinal.aop.Duang;
import com.zcurd.common.util.PasswordUtil;
import com.zcurd.common.util.StringUtil;
import com.zcurd.model.Menu;
import com.zcurd.model.SysLoginLog;
import com.zcurd.model.SysUser;
import com.zcurd.service.LoginService;

/**
 * 登陆
 * @author 钟世云 2016.2.5
 */
public class LoginController extends BaseController {
	
	public void index() {
		setAttr("isShowRandomCode", isShowRandomCode());
		render("login.html");
	}
	
	public void getMenu() {
		//admin用户拥有所有页面
		if("admin".equals(getSessionUser().get("user_name"))) {
			renderJson(Menu.me.findAll());
		}else {
			Object menuList = getSessionAttr("menuList");
			renderJson(menuList);
		}
	}
	
	public void login() {
		String userName = getPara("user_name");
		String remark = "登陆成功";
		
		// 登陆日志
		SysLoginLog log = new SysLoginLog().setUsername(userName)
				.setSessionId(getSession().getId()).setIp(getRemoteAddress()).setCreateTime(new Date());
		
		// 验证验证码
		boolean isShowRandomCode = isShowRandomCode();
		if(isShowRandomCode && (StringUtil.isEmpty(getPara("randomCode")) || !validateCaptcha("randomCode"))) {
			remark = "验证码错误！";
			log.setIsSuccess(0).setRemark(remark).save();
			renderFailed(remark, isShowRandomCode);
			return;
		}
		
		LoginService loginService = Duang.duang(LoginService.class);
		List<SysUser> list = SysUser.me.findByMultiProperties(new String[]{"user_name", "password"}, 
				new Object[]{userName, PasswordUtil.encodePassword(getPara("password"))});
		if(list.size() > 0) {
			setSessionAttr("sysUser", list.get(0));
			//用户菜单
			setSessionAttr("menuList", loginService.getUserMenu(getSessionUser()));
			//页面权限
			List<String> noAuthUrl = loginService.getNoAuthUrl();
			setSessionAttr("noAuthUrl", noAuthUrl);
			//按钮权限
			setSessionAttr("noAuthBtnUrl", loginService.getNoAuthBtnUrl(getSessionUser()));
			//数据权限
			setSessionAttr("noAuthDatarule", loginService.getNoAuthDatarule(getSessionUser()));
			if("admin".equals(getSessionUser().get("user_name"))) {
				setSessionAttr("noAuthUrl", null);
				setSessionAttr("noAuthBtnUrl", null);
				setSessionAttr("pageBtnMap", null);
				setSessionAttr("noAuthDatarule", null);
			}
			addOpLog("登陆系统");
			log.setIsSuccess(1).setRemark(remark).save();
			renderSuccess();
		}else {
			remark = "用户名或密码错误！";
			log.setIsSuccess(0).setRemark(remark).save();
			renderFailed(remark, isShowRandomCode);
		}
	}
	
	public void logout() {
		addOpLog("退出系统");
		removeSessionAttr("sysUser");
		redirect("/login");
	}
	
	/**
	 * 图形验证码
	 */
	public void randomCode() {
		renderCaptcha();
	}
	
	/**
	 * 是否显示图形验证码
	 */
	private boolean isShowRandomCode() {
		LoginService loginService = Duang.duang(LoginService.class);
		return loginService.isShowRandomCode(getSession().getId(), getRemoteAddress());
	}
}
